package com.zhx.demo.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.zhx.app.social.AppSignUpUtils;
import com.zhx.result.Result;
import com.zhx.demo.bindingresult.BindingResultCheckUtil;
import com.zhx.demo.dto.User;
import com.zhx.demo.dto.UserQueryCondition;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户Controller
 *
 * @author zhx
 * @create 2017-11-01 10:19
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AppSignUpUtils appSignUpUtils;

    @PostMapping("/regist")
    public void resign(User user, HttpServletRequest request){
        //不管是用户注册还是绑定 都需要将id返回给spring social
        String userId = user.getUserName();
        appSignUpUtils.doPostSignUp(userId,new ServletWebRequest(request));
    }

    /**
     * JWT 后修改了此处 原@AuthenticationPrincipal
     *
     * @AuthenticationPrincipal 解析spring内部的 用户详情
     *
     *
     *
     * @param user
     * @return
     */
    @GetMapping("/me")
    public Object getCurrentUser(Authentication user,HttpServletRequest request) throws UnsupportedEncodingException {
        //获取Authorization
        String header = request.getHeader("Authorization");

        String token  = StringUtils.substringAfter(header,"Bearer ");

        String signKey = "zhx";

        Claims zhx = Jwts.parser().setSigningKey(signKey.getBytes("UTF-8")).parseClaimsJws(token).getBody();

        String company= (String) zhx.get("company");

        System.out.printf(company);

        return user;
    }


    @GetMapping
    @JsonView(User.UserSimpleView.class)
    @ApiOperation(value="获取用户列表", notes="")
    public Result<List<User>> query(UserQueryCondition condition,
                                    @PageableDefault(page = 2, size = 17, sort = "username,asc") Pageable pageable){

        logger.info("接收到的查询条件是:{}",condition);

        logger.info("接收到的分页条件是:{}",pageable);

        List<User> listUsers = new ArrayList<>();
        listUsers.add(new User("1","zhx1","123",new Date()));
        listUsers.add(new User("2","zhx2","123",new Date()));
        listUsers.add(new User("3","zhx3","123",new Date()));
        return  Result.ok(listUsers);
    }

    @GetMapping("/{id}")
    @JsonView(User.UserDetailView.class)
    public Result<User> queryDetail(@PathVariable String id){
        logger.info("接收到的ID是:{}",id);

        return Result.ok(new User("1","zhx1","123",new Date()));
    }


    @PostMapping
    @JsonView(User.UserDetailView.class)
    public Result<User> saveUser(@Valid @RequestBody User user, BindingResult errors){
        String s = BindingResultCheckUtil.hasErrors(errors);

        if(StringUtils.isNotBlank(s)){
            return  Result.error(s);
        }

        logger.info("得到的保存用户信息:{}",user);

        user.setId("1");
        return Result.ok(user);
    }


    @PutMapping("/{id}")
    @JsonView(User.UserDetailView.class)
    public Result<User> updateUser(@PathVariable String id,@Valid @RequestBody User user, BindingResult errors){
        String s = BindingResultCheckUtil.hasErrors(errors);

        if(StringUtils.isNotBlank(s)){
            return  Result.error(s);
        }

        logger.info("得到的修改用户信息:{}",user);

        user.setId("1");
        return Result.ok(user);
    }


    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable String id){

    }


}
